/* static 属于类的静态方法，静态方法只允许类以属性. 的形式调用；
constructor（）的话 可以构造函数的形式调用*/
import store from '@/store'

export class utils {
  static ua = navigator.userAgent.toLowerCase();

  static objSplit(o) {
    let arr = [];
    for (let key in o) {
      if (o[key]) {
        arr.push(`${key}=${o[key]}`);
      }
    }
    if (arr.length > 0) {
      return `?${arr.join('&')}`;
    }
    return '';
  }

  static urlSearch() {
    var url = decodeURIComponent(window.location.href);
    if (url.includes('from=timeline')) {
      url = url.replace(/\?from=timeline/, '');
    } else if (url.includes('from=singlemessage')) {
      url = url.replace(/\?from=singlemessage/, '');
    }
    var params = {};
    var arr = url.split('?');
    if (arr.length <= 1) {
      return params;
    }
    arr = arr[1].split('&');
    for (var i = 0, l = arr.length; i < l; i++) {
      var a = arr[i].split('=');
      params[a[0]] = a[1];
    }
    return params;
  }

  static setSessionStorage(key, item) {
    sessionStorage.setItem(key, JSON.stringify(item));
  }

  static getSessionStorage(key) {
    return JSON.parse(sessionStorage.getItem(key));
  }


  static delSessionStorage(key) {
    sessionStorage.removeItem(key);
  }

  static setLocalStorage(key, item) {
    let value = localStorage.getItem(key);
    if (!value) {
      localStorage.setItem(key, JSON.stringify(item));
    } else {
      localStorage.setItem(key, JSON.stringify(Object.assign(JSON.parse(value), item)));
    }
  }

  static getLocalStorage(key) {
    return JSON.parse(localStorage.getItem(key));
  }

  static delLocalStorage(key) {
    localStorage.removeItem(key);
  }

  static dateDiff(time) {
    return parseInt((new Date() - time) / 1000 / 60 / 60);
  }

  static ToastGlobal(text, durtion) {
    var node = document.getElementById('toast_self_spial');
    if (!node) {
      node = document.createElement('div');
      node.setAttribute('id', 'toast_self_spial');
    }
    node.style.display = 'block';
    node.style.width = '100%';
    node.style.height = '100%';
    node.style.position = 'fixed';
    node.style.top = '0';
    node.style.left = '0';
    node.style.background = 'rgba(0,0,0,.01)';
    node.style.zIndex = '9999999999999999999';
    // node.innerHTML = text;
    document.body.appendChild(node);
    if (durtion == 0) {
      node.style.display = 'none';
      return;
    }
    durtion = durtion || 1500;
    setTimeout(function () {
      node.style.display = 'none';
    }, durtion);

  }

  static hasSnumber(even) {

    // 规则对象(flag)
    var flag = new RegExp("[`%+~!$^&*={}':;',\\[\\]<>《》/?~！@#￥……&*——{}【】‘；：”“'。，、？ ]")

    // 判断 even 是否包含特殊字符
    if (flag.test(even)) {
      return true;
    } else {
      return false
    }

  }

  static isAndroid() {
    return this.ua.match('android');
  }

  static isTel(num) {
    if (num.length < 11) {
      Toast.info('请输入11位有效数字');
      return false;
    }

    if (!/^1\d{10}/.test(num)) {
      Toast.info('手机号码格式不正确');
      return false;
    }
    let req = /1[3456789]\d{9}$/;
    if (!req.test(num)) {
      Toast.info('手机号不合法');
      return false;
    }
    return true;
  }

  static isName(text) {
    // if (!/^[\u4e00-\u9fa5]{2,20}$/i.test(text)) {
    //   global.log('IsName Error', '输入姓名' + text);
    // }
    return /^[\u4e00-\u9fa5]{2,20}$/i.test(text);
  }


  static numberOne(value) {
    return value && value.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  }

  static logout(value) {
    // var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"); //正则表达式
    // return reg.test(value);
    //
    sessionStorage.removeItem('sys_info')
    sessionStorage.removeItem('info_local')
    // location.href(`/login`)
    location.href = '#/login'


  }

  static numberOne(value) {
    return value && value.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  }

  static getValues(key, arr) {

    let item = arr.find(item => item.value == key);
    if (item) {
      return item.label;
    } else {
      return '';
    }

  }

  static getMsgs(key, arr) {
    if (!arr || arr.length === 0) return '';
    let item = arr.find(item => item.value == key);
    if (item) {
      return item.msg;
    } else {
      return '';
    }

  }

  static getEmumsValue(key) {
    let data = store.getters.enums;
    if (data) {
      return data[key];
    }


  }

  static splitTime(time) {
    if (!time || time.toString().length !== 14) return '';
    const regDate = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/;
    return ('' + time).replace(regDate, "$1-$2-$3 $4:$5:$6");
  }

  static hasNum(obj) {
    // let obj = 'sffds.Mr.sfsf5';
    for (var i = 0; i < obj.length; i++) {
      var temp = obj[i].charCodeAt();
      if (temp >= 48 && temp <= 57) {
        return true
      }
    }
    return false;
  }

  static getStarBankNo(v) {
    return (v + '').replace(/^(.{4}).*(.{3})$/, '$1********$2');
  }

  static toThousands(num) {
    // let n = +(`${num}000`);
    // return (n || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
    return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
  }

  static platType() {
    return 1;
  }

  /**
   * 判断对象是否为空
   * @param obj
   * @returns {boolean}
   */
  static isBlank(obj) {
    if (obj === undefined || obj === null || obj === '') {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 判断对象是非空为空
   * @param obj
   * @returns {boolean}
   */
  static isNotBlank(obj) {
    return !this.isBlank(obj);
  }

  /**
   * 根据map 值获取 value
   * @param key
   * @param map
   * @returns {string|default.msg|string|(function(): string)|*}
   */
  static getMapValue(key, map) {
    let value = map[key];
    return this.isNotBlank(value) ? value : key;
  }

  /**
   * 根据地区码获取地区名
   * @param distractCode
   * @returns {*}
   */
  static getDistractName(distractCode) {
    return this.getMapValue(distractCode, store.getters.allDistrict);
  }

  /**
   * 根据companyId 获取baseInfoCompany 全称
   * @param companyId
   * @returns {companyId|*}
   */
  static getBaseCompanyName(companyId) {
    for (const item of store.getters.baseCompanies) {
      if (companyId === item.companyId) {
        return item.companyName;
      }
    }
    return companyId;
  }

  /**
   * 根据companyId 获取baseInfoCompany 简称
   * @param companyId
   * @returns {companyId|*}
   */
  static getBaseCompanyNameAlias(companyId) {
    let data = store.getters.baseCompanies;
    for (const item of data) {
      if (companyId === item.companyId) {
        return item.companyNameAlias;
      }
    }
    return companyId;
  }

  /**
   * 获取公司id 名称map
   * @returns {null|*}
   */
  static getBaseCompanyMap() {
    let companyMap = {};
    let data = store.getters.baseCompanies;
    for (const item of data) {
      companyMap[item.companyId] = item.companyNameAlias;
    }
    return companyMap;
  }

  /**
   * 获取公司id 名称map json STR
   * @returns {null|*}
   */
  static getBaseCompanyMapJsonStr() {
    return JSON.stringify(this.getBaseCompanyMap());
  }

  /**
   * 判断对象是否在数组中
   * @param arr
   * @param value
   * @returns {boolean}
   */
  static isInArray(arr, value) {
    for (let i = 0; i < arr.length; i++) {
      if (value === arr[i]) {
        return true;
      }
    }
    return false;
  }

  /**
   * 过滤无效字符字符集
   * @param value
   * @returns {string|*}
   */
  static filterEmptyData(value) {

    if (this.isBlank(value) || this.isInArray(['undefined', 'null', 'unknown'], value)) {
      return '';
    } else {
      return value;
    }
  }

  /**
   * 结果集合中YYYYMMDD类型日期转换为字符串
   * @param item
   * @param keyArray
   */
  static longDateToStr(item, keyArray) {
    for (const key of keyArray) {
      let value = item[key];
      if (this.isNotBlank(value)) {
        // item[key] = moment(value, 'YYYYMMDD').toDate();
        item[key] = value + '';
      }
    }
  }

  /**
   * 根据key值获取list集合种对应字段值
   * @param key           key值
   * @param list          list集合
   * @param keyColum      key值对应的字段名   [default：id]
   * @param valueColum    value值对应的字段名 [default：name]
   * @returns {*}         value值
   */
  static getListValue(key, list, keyColum, valueColum) {
    if (this.isBlank(keyColum)) {
      keyColum = "id";
    }
    if (this.isBlank(valueColum)) {
      valueColum = "name";
    }
    for (const item of list) {
      if (item[keyColum] === key) {
        let value = item[valueColum];
        return this.isNotBlank(value) ? value : key;
      }
    }
  }

  /**
   * 根据时间戳获取所在月份的最后一天的最后一毫秒的时间戳
   * @param timestamp
   */
  static getMonthEndTime(timestamp) {
    return moment(timestamp).endOf("month").endOf("millisecond").valueOf();
  }

  /**
   * 计算时间戳相差天数
   * @param timestamp1
   * @param timestamp2
   * @returns {number}
   */
  static calcDay(timestamp1, timestamp2) {
    // 将时间戳相减获得差值（毫秒数）
    let differ = timestamp1 - timestamp2
    /**
     * @desc 毫秒数除以1000就转为秒数
     * @desc 秒数除以60后取整，就是分钟（因为1分钟等于60秒）
     * @desc 秒数除以3600后取整，就是小时（因为1小时等于3600秒）
     * @desc 小时数除以24后取整，就是相差的天数
     */
    let day = differ / 1000 / 60 / 60 / 24
    return parseInt(day);
  }

  /**
   * 获取当天零点时间
   * @returns {Date}
   */
  static getFirstDay() {
    return new Date(new Date().setHours(0, 0, 0, 0));
  }

  /**
   * 获取当天23点59分59秒时间
   * @returns {Date}
   */
  static getLastDay() {
    return new Date(new Date().setHours(23, 59, 59, 999));
  }

  /**
   * 获取本周周一零点时间
   * @returns {Date}
   */
  static getThisWeekFirstDay() {
    let today = new Date();
    let day = today.getDay() || 7;
    return new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1 - day);
  }

  /**
   * 获取本月一号零点时间
   * @returns {Date}
   */
  static getThisMonthFirstDay() {
    let today = new Date();
    today.setDate(1);
    today.setHours(0, 0, 0, 0);
    return today;
  }

  /**
   * 获取本年一号零点时间
   * @returns {Date}
   */
  static getThisYearFirstDay() {
    let today = new Date();
    today.setDate(1);
    today.setMonth(0);
    today.setHours(0, 0, 0, 0);
    return today;
  }

}
